package com.jamal2362.apktool.util;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.task.IconTask;

public class FilePicker extends ListView {
	private String rootDir;
	private String[] extFilter;
	private FilesAdapter adapter;
	private ArrayList<String> filesArray;
	private Context mContext;
	private int textSize;
	private AlertDialog dialog;
	private Runnable callback;
	private IconFactory iconFactory;

	public FilePicker(Context context) {
		super(context);
		setDivider(null);
		setDividerHeight(0);
		this.mContext = context;
		this.rootDir = Settings.gets(context, "picker_path", Environment.getExternalStorageDirectory().getAbsolutePath());
		this.textSize = Settings.appFontSize;
		this.iconFactory = new IconFactory(mContext);
		this.iconFactory.round(Settings.roundIcons);
		this.filesArray = new ArrayList<String>();
		this.adapter = new FilesAdapter(context, R.id.details, filesArray);
		setAdapter(adapter);
		new Handler().postDelayed(new Runnable()
			{
				@Override
				public void run() {
					refresh(new File(rootDir));
				}
			}, 300);
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(adapter);
	}

	public void textSize(int size) {
		this.textSize = size;
	}

	public void setDialog(AlertDialog d) {
		this.dialog = d;
	}

	public void setFilter(String[] filter) {
		if (filter != null && filter.length == 0)
			return;
		this.extFilter = filter;
	}

	public void setCallback(Runnable clb) {
		this.callback = clb;
	}

	public void setPath(String path) {
		this.rootDir = path;
	}

	public String getPath() {
		return this.rootDir;
	}

	public void refresh(File file) {
		rootDir = file.getAbsolutePath();
		if (file.isDirectory()) {
			Settings.sets(mContext, "picker_path", file.getAbsolutePath());
			adapter = new FilesAdapter(mContext, R.id.details, createList(file));
			setAdapter(adapter);
		} else {
			Settings.sets(mContext, "picker_path", file.getParent());
			callback.run();
			dialog.cancel();
		}
	}

	private ArrayList<String> createList(File dir) {
		String[] storages = FileUtils.getStorages(mContext);
		ArrayList<String> res = new ArrayList<String>();
		if (storages != null) {
			boolean add = true;
			for (int i = 0; i < storages.length; i++) {
				if (dir.getAbsolutePath().equals(storages[i]))
					add = false;
			}
			if (add)
				res.add(0, " ..");
		}
		FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File file) {
				if (extFilter != null && file.isFile()) {
					String p2 = file.getName();
					for (String ext : extFilter) {
						if (p2.toLowerCase().endsWith("." + ext.toLowerCase()))
							return true;
					}
				}
				return file.isDirectory();
			}
		};
		File[] list = dir.listFiles(filter);
		if (list != null) {
			Arrays.sort(list);
			for (File file : list) {
				if (file.isDirectory())
					res.add(file.getName());
			}
			for (File file : list) {
				if (!file.isDirectory())
					res.add(file.getName());
			}
		}
		return res;
	}

	private class FilesAdapter extends ArrayAdapter<String> {
		private List<String> objects = null;

		public FilesAdapter(Context context, int textviewid, List<String> objects) {
			super(context, textviewid, objects);
			this.objects = objects;
		}

		@Override
		public int getCount() {
			return ((null != objects) ? objects.size() : 0);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public String getItem(int position) {
			return ((null != objects) ? objects.get(position) : null);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (null == view) {
				LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.files_entry, null);
			}
			int dft = textSize - 4;
			int minh = MUtil.spAsPx(mContext, (textSize * 2 + dft));
			view.setMinimumHeight(minh);
			String data = objects.get(position);
			if (null != data && !TextUtils.isEmpty(data)) {
				File root = new File(rootDir);
				final boolean viewBack = (position == 0 && !root.equals(Environment.getExternalStorageDirectory()));
				final File file = (viewBack ? root.getParentFile() : new File(rootDir, data));
				final TextView textview = view.findViewById(R.id.details);
				textview.setText(file.getAbsolutePath());
				textview.setTextSize(TypedValue.COMPLEX_UNIT_SP, dft);
				if (viewBack)
					textview.setVisibility(View.GONE);
				final TextView name = view.findViewById(R.id.name);
				name.setText(data);
				name.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
				final ImageView icon = view.findViewById(R.id.icon);
				icon.setTag(file.getAbsolutePath());
				if (file.isDirectory() || viewBack) {
					icon.setImageBitmap(iconFactory.makeIcon((Settings.lightTheme ? IconTypes.colorFolderLight : IconTypes.colorFolderDark), R.drawable.ic_folder));
				} else {
					String n = data.toLowerCase();
					int[] types = IconTypes.getType(n);
					icon.setImageBitmap(iconFactory.makeIcon(types[1], types[0]));
					if (n.endsWith(".apk") || n.endsWith(".apks") || n.endsWith(".xapk") || types[0] == R.drawable.ic_image) {
						IconTask itask = new IconTask(mContext, icon);
						itask.execute(file);
					}
				}
				view.setOnClickListener(new OnClickListener()
					{
						@Override
						public void onClick(View p1) {
							refresh(file);
						}
					});
				view.setOnLongClickListener(new OnLongClickListener()
					{
						@Override
						public boolean onLongClick(View p1) {
							if (file.isDirectory() && extFilter == null && !viewBack) {
								rootDir = file.getAbsolutePath();
								Settings.sets(mContext, "picker_path", file.getParent());
								callback.run();
								dialog.cancel();
							}
							return true;
						}
					});
			}
			return view;
		}
	}
}
